<template>
  <div class="p-4 bg-gray-50 min-h-screen">
    <div class="max-w-6xl mx-auto">
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">智慧食堂收入管理系统</h1>
        <div class="flex items-center space-x-2">
          <el-tag type="success">实时数据</el-tag>
          <span class="text-sm text-gray-500">{{ currentTime }}</span>
        </div>
      </div>

      <!-- 收入概览卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-blue-100 p-3 rounded-full mr-4">
              <i class="fas fa-money-bill-wave text-blue-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">累计总收入</p>
              <h3 class="text-2xl font-bold mt-1">¥ {{ stats.totalIncome }}</h3>
            </div>
          </div>
        </el-card>

        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-green-100 p-3 rounded-full mr-4">
              <i class="fas fa-shopping-cart text-green-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">订单总数</p>
              <h3 class="text-2xl font-bold mt-1">{{ stats.totalOrders }}</h3>
            </div>
          </div>
        </el-card>

        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-purple-100 p-3 rounded-full mr-4">
              <i class="fas fa-receipt text-purple-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">平均订单金额</p>
              <h3 class="text-2xl font-bold mt-1">¥ {{ stats.avgOrderValue }}</h3>
            </div>
          </div>
        </el-card>

        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-yellow-100 p-3 rounded-full mr-4">
              <i class="fas fa-star text-yellow-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">最受欢迎菜品</p>
              <h3 class="text-2xl font-bold mt-1">{{ stats.topDish }}</h3>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 收入趋势图表 -->
      <el-card shadow="hover" class="mb-6">
        <div class="flex justify-between items-center mb-4">
          <div>
            <h2 class="text-xl font-semibold text-gray-700">收入趋势分析</h2>
            <p class="text-gray-500 text-sm mt-1">近30天食堂收入变化趋势</p>
          </div>
          <div class="flex space-x-2">
            <el-radio-group v-model="timeRange" size="small">
              <el-radio-button label="day">按日</el-radio-button>
              <el-radio-button label="week">按周</el-radio-button>
              <el-radio-button label="month">按月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="income-trend" class="w-full" style="height: 350px"></div>
      </el-card>

      <!-- 菜品收入分布 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <el-card shadow="hover">
          <div class="mb-4">
            <h2 class="text-xl font-semibold text-gray-700">菜品收入分布</h2>
            <p class="text-gray-500 text-sm mt-1">各类菜品对总收入的贡献比例</p>
          </div>
          <div id="dish-income" class="w-full" style="height: 300px"></div>
        </el-card>

        <el-card shadow="hover">
          <div class="mb-4">
            <h2 class="text-xl font-semibold text-gray-700">热门菜品收入排行</h2>
            <p class="text-gray-500 text-sm mt-1">收入最高的菜品TOP 10</p>
          </div>
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">菜品</th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单数量</th>
                  <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总收入</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="(dish, index) in topDishes" :key="index" :class="index < 3 ? 'bg-yellow-50' : ''">
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                      <span class="text-sm font-medium text-gray-900">{{ dish.name }}</span>
                    </div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full" :class="dishTypeClass(dish.type)">
                      {{ dishTypeLabel(dish.type) }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ dish.orderCount }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">¥ {{ dish.totalIncome }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import * as echarts from 'echarts';
import request from '@/utils/request';

// 当前时间
const currentTime = ref('');
// 时间范围选项
const timeRange = ref('day');
// 统计信息
const stats = ref({
  totalIncome: 0,
  totalOrders: 0,
  avgOrderValue: 0,
  topDish: ''
});
// 热门菜品
const topDishes = ref([]);

// 菜品类型映射
const dishTypes = [
  { id: 0, name: '猪肉类', color: 'bg-red-100 text-red-800' },
  { id: 1, name: '牛肉类', color: 'bg-orange-100 text-orange-800' },
  { id: 2, name: '羊肉类', color: 'bg-yellow-100 text-yellow-800' },
  { id: 3, name: '蔬菜类', color: 'bg-green-100 text-green-800' },
  { id: 4, name: '鱼类', color: 'bg-blue-100 text-blue-800' },
  { id: 5, name: '豆制品', color: 'bg-indigo-100 text-indigo-800' },
  { id: 6, name: '蛋类', color: 'bg-purple-100 text-purple-800' },
  { id: 7, name: '主食类', color: 'bg-pink-100 text-pink-800' }
];

// 菜品类型标签
const dishTypeLabel = (typeId) => {
  const type = dishTypes.find(t => t.id === typeId);
  return type ? type.name : '其他';
};

// 菜品类型样式
const dishTypeClass = (typeId) => {
  const type = dishTypes.find(t => t.id === typeId);
  return type ? type.color : 'bg-gray-100 text-gray-800';
};

// 图表实例
let incomeTrendChart = null;
let dishIncomeChart = null;

// 收入趋势图表配置
const trendOption = {
  title: {
    text: '近30天收入趋势',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}<br/>¥ {c}',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#ddd',
    borderWidth: 1,
    textStyle: {
      color: '#333'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#ccc'
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '收入 (元)',
    nameTextStyle: {
      fontSize: 12
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: '#ccc'
      }
    },
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: '收入',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#36a2eb'
      },
      lineStyle: {
        width: 3,
        color: '#36a2eb'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(54, 162, 235, 0.5)' },
          { offset: 1, color: 'rgba(54, 162, 235, 0.1)' }
        ])
      },
      symbol: 'circle',
      symbolSize: 8
    }
  ]
};

// 菜品收入分布图表配置
const dishOption = {
  title: {
    text: '菜品收入分布',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: ¥{c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    right: 10,
    top: 'center',
    data: []
  },
  series: [
    {
      name: '收入分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
};

// 加载数据
const loadData = async () => {
  try {
    // 模拟API请求 - 实际项目中应替换为真实API
    // const res = await request.get("/admin/income");
    
    // 模拟数据 - 基于提供的数据库结构
    const mockData = {
      totalIncome: 380,
      totalOrders: 20,
      avgOrderValue: 19,
      topDish: "回锅肉",
      dailyIncome: [
        { date: '2025-07-02', income: 33 },
        { date: '2025-07-03', income: 8 },
        { date: '2025-07-04', income: 18 },
        { date: '2025-07-05', income: 18 },
        { date: '2025-07-06', income: 43 },
        { date: '2025-07-07', income: 25 },
        { date: '2025-07-08', income: 16 },
        { date: '2025-07-09', income: 86 },
        { date: '2025-07-10', income: 17 }
      ],
      dishIncome: [
        { type: 0, name: '猪肉类', value: 119 },
        { type: 1, name: '牛肉类', value: 41 },
        { type: 2, name: '羊肉类', value: 42 },
        { type: 3, name: '蔬菜类', value: 17 },
        { type: 4, name: '鱼类', value: 32 },
        { type: 5, name: '豆制品', value: 62 },
        { type: 6, name: '蛋类', value: 15 },
        { type: 7, name: '主食类', value: 52 }
      ],
      topDishes: [
        { name: '回锅肉', type: 0, orderCount: 6, totalIncome: 30 },
        { name: '豆泡', type: 5, orderCount: 8, totalIncome: 16 },
        { name: '烤羊头', type: 2, orderCount: 6, totalIncome: 60 },
        { name: '炒米粉', type: 7, orderCount: 7, totalIncome: 7 },
        { name: '东坡肉', type: 0, orderCount: 5, totalIncome: 25 },
        { name: '泡椒鱼片', type: 4, orderCount: 5, totalIncome: 20 },
        { name: '茶叶蛋', type: 6, orderCount: 6, totalIncome: 12 },
        { name: '羊肉串', type: 2, orderCount: 3, totalIncome: 18 },
        { name: '麻婆豆腐', type: 5, orderCount: 3, totalIncome: 3 },
        { name: '闽南猪蹄', type: 0, orderCount: 2, totalIncome: 14 }
      ]
    };

    // 更新统计数据
    stats.value = {
      totalIncome: mockData.totalIncome,
      totalOrders: mockData.totalOrders,
      avgOrderValue: mockData.avgOrderValue,
      topDish: mockData.topDish
    };

    // 更新热门菜品
    topDishes.value = mockData.topDishes;

    // 更新收入趋势图表
    trendOption.xAxis.data = mockData.dailyIncome.map(item => item.date);
    trendOption.series[0].data = mockData.dailyIncome.map(item => item.income);
    if (incomeTrendChart) {
      incomeTrendChart.setOption(trendOption);
    }

    // 更新菜品收入分布图表
    dishOption.legend.data = mockData.dishIncome.map(item => item.name);
    dishOption.series[0].data = mockData.dishIncome.map(item => ({
      name: item.name,
      value: item.value
    }));
    if (dishIncomeChart) {
      dishIncomeChart.setOption(dishOption);
    }

    console.log('收入数据加载成功');
  } catch (error) {
    console.error('收入数据加载失败:', error);
  }
};

// 更新时间
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 初始化图表
const initCharts = () => {
  const trendDom = document.getElementById('income-trend');
  if (trendDom) {
    incomeTrendChart = echarts.init(trendDom);
    incomeTrendChart.setOption(trendOption);
  }

  const dishDom = document.getElementById('dish-income');
  if (dishDom) {
    dishIncomeChart = echarts.init(dishDom);
    dishIncomeChart.setOption(dishOption);
  }

  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    if (incomeTrendChart) incomeTrendChart.resize();
    if (dishIncomeChart) dishIncomeChart.resize();
  });
};

// 设置定时器
let timeTimer = null;

onMounted(() => {
  initCharts();
  loadData();
  
  // 更新时间
  updateTime();
  timeTimer = setInterval(updateTime, 1000);
});

onBeforeUnmount(() => {
  if (timeTimer) clearInterval(timeTimer);
  if (incomeTrendChart) incomeTrendChart.dispose();
  if (dishIncomeChart) dishIncomeChart.dispose();
});
</script>

<style scoped>
.el-card {
  border-radius: 10px;
  border: none;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

#income-trend, #dish-income {
  border-radius: 8px;
  background-color: #fff;
}

table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e1e1e1;
}

thead th {
  background-color: #f8f9fa;
  position: sticky;
  top: 0;
}

tbody tr:hover {
  background-color: #f5f7fa;
}

tbody tr:nth-child(1) {
  font-weight: bold;
  color: #e6a23c;
}

tbody tr:nth-child(2) {
  font-weight: bold;
  color: #909399;
}

tbody tr:nth-child(3) {
  font-weight: bold;
  color: #cd7f32;
}
</style>